/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DataFrame.java
 *
 * Created on 2010-4-21, 21:27:15
 */

package fusiondata;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Administrator
 */
public class DataFrame extends javax.swing.JFrame {

    /** Creates new form DataFrame */
    private DataFromDB df;
    private JPanel fatherPanel;

    public DataFrame() {
        initComponents();
        buttonGroup1.add(this.RButton1);
        buttonGroup1.add(this.RButton2);
    }

    public DataFrame(DataFromDB df, JPanel fatherPanel) {
        this.df = df;
        this.fatherPanel = fatherPanel;

        initComponents();
        buttonGroup1.add(this.RButton1);
        buttonGroup1.add(this.RButton2);
        this.setResizable(false);

    }

    private Vector<String> getTables(){
        ResultSet rs = df.getStructure();
        Vector<String> tables = new Vector<String>();
        try {
            while (rs.next()) {
                tables.add(rs.getString(3));
            }
            return tables;
        } catch (SQLException ex) {
            return null;
        }
    }

    private Vector<String> getColumns(String tableName){
        ResultSet rs = df.getColumns(tableName);
        Vector<String> tables = new Vector<String>();
        try {
            while (rs.next()) {
                tables.add(rs.getString(4));
            }
            return tables;
        } catch (SQLException ex) {
            return null;
        }
    }

private DefaultTableModel excuteResultSet(ResultSet rs){
        DefaultTableModel tableModel = null;
        try {
            ResultSetMetaData rsm = rs.getMetaData();
            int columns = rsm.getColumnCount();

            Vector columnNames = new Vector();
            for(int i = 1;i <= columns;i++ ){
//                tableModel.addColumn(rsm.getColumnName(i));
                columnNames.add(rsm.getColumnName(i));
                System.out.println(rsm.getColumnName(i));
            }

            tableModel = new DefaultTableModel(columnNames,0);

            while(rs.next()){
                Vector v = new Vector();
                for(int i = 1;i <= columns;i++){
                    v.add(rs.getObject(i));
                }
                tableModel.addRow(v);
            }
        } catch (SQLException ex) {
            Logger.getLogger(viewDataFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        return tableModel;
    }

  /*
   *
   **/
    private void getData(int style){
        String sql = "";
        if(RButton1.isSelected())
        {
            DefaultListModel choseModel = (DefaultListModel)choseList.getModel();
            String column = "";
            for(int i = 0;i < choseModel.size();i++){
                if(i == choseModel.size()-1){
                    column += choseModel.getElementAt(i);
                }else{
                    column += choseModel.getElementAt(i) + ",";
                }
            }
            sql = "select " + column +" from " + tableBox.getSelectedItem().toString();
            System.out.println(sql);
//            ResultSet rs = df.getResultSet(sql);
//            new viewDataFrame(excuteResultSet(rs)).setVisible(true);
        }
        else if(RButton2.isSelected())
        {
            sql = sqlTextArea.getText().trim();
            System.out.println(sql);
//            ResultSet rs = df.getResultSet(sql);
//            new viewDataFrame(excuteResultSet(rs)).setVisible(true);
        }
        ResultSet rs = df.getResultSet(sql);
        if(style == 0)
        {
            new viewDataFrame(excuteResultSet(rs)).setVisible(true);
        }
        else if(style == 1)
        {
            DefaultTableModel dataModel = excuteResultSet(rs);
            String title = JOptionPane.showInputDialog(this, "请输入加载数据的标题");
            fatherPanel.add(new DataJInternalFrame(dataModel, title));
        }
        
    }

    private void moveItems(int direction){
        //        columnList choseList
        //
        DefaultListModel columnModel = (DefaultListModel) columnList.getModel();
        DefaultListModel choseModel = (DefaultListModel)choseList.getModel();

        switch (direction){
            case 0:{//右移选项
                for(int i:columnList.getSelectedIndices()){
                    choseModel.addElement(columnModel.get(i));
                    columnModel.remove(i);
                }
                columnList.updateUI();
                choseList.updateUI();
                break;
            }

            case 1:{//右移全部选项
                for(Object obj:columnModel.toArray())
                    choseModel.addElement(obj);
                columnModel.removeAllElements();
                columnList.updateUI();
                choseList.updateUI();
                break;
            }

            case 2:{//左移选项
                for(int i:choseList.getSelectedIndices()){
                    columnModel.addElement(choseModel.get(i));
                    choseModel.remove(i);
                }
                columnList.updateUI();
                choseList.updateUI();
                break;
            }
            
            case 3:{//左移全部选项
                for(Object obj:choseModel.toArray())
                    columnModel.addElement(obj);
                choseModel.removeAllElements();
                columnList.updateUI();
                choseList.updateUI();
                break;
            }
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        buttonGroup1 = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        tableBox = new javax.swing.JComboBox(getTables());
        jScrollPane1 = new javax.swing.JScrollPane();
        DefaultListModel dlm = new DefaultListModel();
        for(Object i:getColumns(tableBox.getSelectedItem().toString()).toArray())
        dlm.addElement(i);
        columnList = new javax.swing.JList(dlm);
        jScrollPane2 = new javax.swing.JScrollPane();
        choseList = new javax.swing.JList(new DefaultListModel());
        jScrollPane4 = new javax.swing.JScrollPane();
        sqlTextArea = new javax.swing.JTextArea();
        RButton1 = new javax.swing.JRadioButton();
        RButton2 = new javax.swing.JRadioButton();
        jLabel2 = new javax.swing.JLabel();
        rightButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        rightAllButton = new javax.swing.JButton();
        leftButton = new javax.swing.JButton();
        leftAllButton = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        getDataButton = new javax.swing.JButton();
        viewDataButton = new javax.swing.JButton();

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.setName("jTextArea1"); // NOI18N
        jScrollPane3.setViewportView(jTextArea1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(fusiondata.FusionDataApp.class).getContext().getResourceMap(DataFrame.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        tableBox.setName("tableBox"); // NOI18N
        tableBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                tableBoxItemStateChanged(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        columnList.setName("columnList"); // NOI18N
        jScrollPane1.setViewportView(columnList);

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        choseList.setName("choseList"); // NOI18N
        jScrollPane2.setViewportView(choseList);

        jScrollPane4.setName("jScrollPane4"); // NOI18N

        sqlTextArea.setColumns(20);
        sqlTextArea.setRows(5);
        sqlTextArea.setName("sqlTextArea"); // NOI18N
        jScrollPane4.setViewportView(sqlTextArea);

        RButton1.setSelected(true);
        RButton1.setText(resourceMap.getString("RButton1.text")); // NOI18N
        RButton1.setName("RButton1"); // NOI18N

        RButton2.setText(resourceMap.getString("RButton2.text")); // NOI18N
        RButton2.setName("RButton2"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        rightButton.setText(resourceMap.getString("rightButton.text")); // NOI18N
        rightButton.setName("rightButton"); // NOI18N
        rightButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rightButtonActionPerformed(evt);
            }
        });

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        rightAllButton.setText(resourceMap.getString("rightAllButton.text")); // NOI18N
        rightAllButton.setName("rightAllButton"); // NOI18N
        rightAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rightAllButtonActionPerformed(evt);
            }
        });

        leftButton.setText(resourceMap.getString("leftButton.text")); // NOI18N
        leftButton.setName("leftButton"); // NOI18N
        leftButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                leftButtonActionPerformed(evt);
            }
        });

        leftAllButton.setText(resourceMap.getString("leftAllButton.text")); // NOI18N
        leftAllButton.setName("leftAllButton"); // NOI18N
        leftAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                leftAllButtonActionPerformed(evt);
            }
        });

        jButton5.setText(resourceMap.getString("jButton5.text")); // NOI18N
        jButton5.setName("jButton5"); // NOI18N

        getDataButton.setText(resourceMap.getString("getDataButton.text")); // NOI18N
        getDataButton.setName("getDataButton"); // NOI18N
        getDataButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                getDataButtonActionPerformed(evt);
            }
        });

        viewDataButton.setText(resourceMap.getString("viewDataButton.text")); // NOI18N
        viewDataButton.setName("viewDataButton"); // NOI18N
        viewDataButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewDataButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(RButton1)
                    .addComponent(RButton2)
                    .addComponent(jScrollPane4)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tableBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(leftAllButton)
                                    .addComponent(rightAllButton)
                                    .addComponent(rightButton)
                                    .addComponent(leftButton)))
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(19, Short.MAX_VALUE)
                .addComponent(viewDataButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(getDataButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton5)
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {leftAllButton, leftButton, rightAllButton, rightButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(RButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tableBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(rightButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rightAllButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(leftButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(leftAllButton))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(RButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton5)
                    .addComponent(getDataButton)
                    .addComponent(viewDataButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tableBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_tableBoxItemStateChanged
//         columnList
        String tableName = tableBox.getSelectedItem().toString();
        Vector<String> columsName = getColumns(tableName);
        DefaultListModel lm = new DefaultListModel();
        DefaultListModel choseModel = (DefaultListModel)choseList.getModel();
        choseModel.removeAllElements();
        for(String item:columsName)
            lm.addElement(item);
        columnList.setModel(lm);
        columnList.updateUI();

    }//GEN-LAST:event_tableBoxItemStateChanged

    private void rightButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rightButtonActionPerformed
         moveItems(0);
    }//GEN-LAST:event_rightButtonActionPerformed

    private void rightAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rightAllButtonActionPerformed
        moveItems(1);
    }//GEN-LAST:event_rightAllButtonActionPerformed

    private void leftButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_leftButtonActionPerformed
        moveItems(2);
    }//GEN-LAST:event_leftButtonActionPerformed

    private void leftAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_leftAllButtonActionPerformed
        moveItems(3);
    }//GEN-LAST:event_leftAllButtonActionPerformed

    private void viewDataButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewDataButtonActionPerformed
        getData(0);
    }//GEN-LAST:event_viewDataButtonActionPerformed

    private void getDataButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getDataButtonActionPerformed
        getData(1);
    }//GEN-LAST:event_getDataButtonActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DataFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JRadioButton RButton1;
    private javax.swing.JRadioButton RButton2;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JList choseList;
    private javax.swing.JList columnList;
    private javax.swing.JButton getDataButton;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JButton leftAllButton;
    private javax.swing.JButton leftButton;
    private javax.swing.JButton rightAllButton;
    private javax.swing.JButton rightButton;
    private javax.swing.JTextArea sqlTextArea;
    private javax.swing.JComboBox tableBox;
    private javax.swing.JButton viewDataButton;
    // End of variables declaration//GEN-END:variables

}
